﻿using System;
using System.Windows.Forms;
using System.Linq;
using System.Collections.Generic;
using System.Threading;
using System.Drawing;
using System.Net;
using System.IO;

namespace HRN.Bot {
    public partial class MainMenu {
        #region Variable
        private int WaitingAmount = 0;
        internal List<UrlHistory> urlhistory = new List<UrlHistory>(); 
        private Random randm = new Random();
        #endregion
        internal MainMenu() {
            InitializeComponent();
        }
        public void setproxy() {
            try {
                string ip = listBoxProxy.SelectedItem.ToString().Split(':').First();
                string port = listBoxProxy.SelectedItem.ToString().Split(':').Last();
                HRNProxy.SetProxy(ip.ToString(), Convert.ToInt16(port.ToString()));        ///////////////////
                InfostoolStripStatusLabel.Text = "Wait for loading proxy...";
                Delay(1);
                IsNavigate();
            } catch (Exception ex) {
                InfostoolStripStatusLabel.Text = "Bad Proxy!" + ex.Message + " "+ ex.InnerException;
                Delay(1);
                listBoxProxy.Items.Remove(listBoxProxy.SelectedIndex);
            }
        }
        private void IsNavigate() {
            if (IsCanClick()) 
                ClickSkipButton();
            navigate(ListBoxURL.SelectedItem.ToString());
        }
        private bool IsCanClick() {
            if (WebBrowser1.Document != null && WebBrowser1.Document.Body != null && (WebBrowser1.Document.GetElementById("skip_ad_button") != null || WebBrowser1.Document.GetElementById("skip_button") != null || WebBrowser1.Document.GetElementById("close_bar();") != null))
                return true;
            return false;
        }
        private void URLProxySelectedIndexControl() {
            URLSelectedIndexControl();
            ProxySelectedIndexControl();
        }
        private void URLSelectedIndexControl() {
            if (ListBoxURL.Items.Count <= 0 || ListBoxURL.SelectedIndex < 0)
                ListBoxURL.SelectedIndex = 0;
            else {
                if (ListBoxURL.SelectedIndex + 1 >= ListBoxURL.Items.Count)
                    ListBoxURL.SelectedIndex = 0;/// ListBoxURL.SelectedIndex = randm.Next(0, ListBoxURL.Items.Count + 1);
                else
                    ListBoxURL.SelectedIndex = ListBoxURL.SelectedIndex + 1;
            }
        }
        private void ProxySelectedIndexControl() {
            if (listBoxProxy.Items.Count <= 0 || listBoxProxy.SelectedIndex < 0)
                listBoxProxy.SelectedIndex = 0;
            else {
                listBoxProxy.SelectedIndex = randm.Next(0, listBoxProxy.Items.Count + 1); ;
                while (urlhistory[0].HasProxyInUrl(urlhistory, ListBoxURL.SelectedItem.ToString(), listBoxProxy.SelectedItem.ToString()) && !HRNProxy.PingHost(listBoxProxy.SelectedItem.ToString().Split(':').First(), Convert.ToInt32(listBoxProxy.SelectedItem.ToString().Split(':').Last())))
                    listBoxProxy.SelectedIndex = listBoxProxy.SelectedIndex + 1; // randm.Next(0, listBoxProxy.Items.Count + 1); ;
                //while (!HRNProxy.PingHost(listBoxProxy.SelectedItem.ToString().Split(':').First(), Convert.ToInt32(listBoxProxy.SelectedItem.ToString().Split(':').Last())))
                //    listBoxProxy.SelectedIndex = listBoxProxy.SelectedIndex + 1; // randm.Next(0, listBoxProxy.Items.Count + 1); ;  
            }
        }
        private object Start() {
            if (RequestCounterTypeControl() && Convert.ToInt32(textBoxRequestCounter.Text) > 0 && ListBoxURL.Items.Count > 0 && listBoxProxy.Items.Count > 0 && ClickWaitTypeControl() && Convert.ToInt32(textBoxClickWait.Text) > 0) {
                try {
                    while ((Convert.ToInt32(GoodCountertoolStripStatusLabel.Text)) < Convert.ToInt32(textBoxRequestCounter.Text) + 1) {
                        URLProxySelectedIndexControl();
                        setproxy();
                    }
                } catch {
                    InfostoolStripStatusLabel.Text = "Request Counter Not Null!";
                }
            } else
                InfostoolStripStatusLabel.Text = "Request Counter not Zero OR Url Or Proxy Not Found!";
            return null;
        }
        private void navigate(string url) {
            WebBrowser1.Navigate(url);
            InfostoolStripStatusLabel.Text = "Navigating browser...";
            GroupBox3.Text = "Browser - Url : " + ListBoxURL.SelectedItem.ToString() + " - Proxy : " + listBoxProxy.SelectedItem.ToString();
            Wait(WaitingAmount = randm.Next(3, Convert.ToInt32(textBoxDelay.Text)));
        }

        private void Wait(int count) {
            DateTime nowdt = DateTime.MinValue;
            while (WebBrowser1.ReadyState != WebBrowserReadyState.Complete && WebBrowser1.ReadyState != WebBrowserReadyState.Uninitialized) {
                if (nowdt == DateTime.MinValue)
                    nowdt = DateTime.Now;
                WaitCountertoolStripStatusLabel4.Text = ((DateTime.Now.TimeOfDay.Minutes - nowdt.TimeOfDay.Minutes) * 60 + DateTime.Now.TimeOfDay.Seconds - nowdt.TimeOfDay.Seconds).ToString();
                if (Convert.ToInt32(WaitCountertoolStripStatusLabel4.Text) > count || Convert.ToInt32(WaitCountertoolStripStatusLabel4.Text) < -count)
                    break;
                Application.DoEvents();
            }
        }
        private void runBrowserThread(Uri url) {
            var th = new Thread(() => {
                WebBrowser1.Navigate(url);
                Application.Run();
            });
            th.SetApartmentState(ApartmentState.STA);
            th.Start();
        }
        private void ClickSkipButton() {
            try {
                if (IsCanClick())
                    ClickedSkipButton();
            } catch (Exception ex) {
                InfostoolStripStatusLabel.Text = "Exception! " + ex.ToString();
                BadCountertoolStripStatusLabel.Text = (Convert.ToInt32(BadCountertoolStripStatusLabel.Text) + 1).ToString();
                //AddHistoryAndBar();       /////////////////////////
            }
        }
        private void AddHistoryAndBar() {
            Delay(1);
            AddHistory();
            ProgressBarControl();
        }
        private void ClickedSkipButton() {
            if (Click()) {
                GoodCountertoolStripStatusLabel.Text = (Convert.ToInt32(GoodCountertoolStripStatusLabel.Text) + 1).ToString();
                InfostoolStripStatusLabel.Text = "Skip Button clicked :)))";
                AddHistoryAndBar();
            }
        }
        private bool Click() {
            if (IsCanClick()) {
                if (WebBrowser1.Document.GetElementById("skip_ad_button") != null) {
                    WebBrowser1.Document.GetElementById("skip_ad_button").InvokeMember("click");
                }
                //if (WebBrowser1.Document.GetElementById("skip_button") != null) {
                //    WebBrowser1.Document.GetElementById("skip_button").InvokeMember("click");
                //} 
                if (WebBrowser1.Document.GetElementById("close_bar();") != null) {
                    WebBrowser1.Document.GetElementById("close_bar();").InvokeMember("click");
                }
                Wait(WaitingAmount = randm.Next(3, Convert.ToInt32(textBoxClickWait.Text)));
                return true;
            } 
            return false;
        }
        private void ProgressBarControl() {
            toolStripProgressBar1.Value += 1;
            //if (toolStripProgressBar1.Value >= (Convert.ToInt32(textBoxRequestCounter.Text) / 2))
            //    toolStripProgressBar1.ForeColor = System.Drawing.Color.Blue;
            //else if (toolStripProgressBar1.Value >= (Convert.ToInt32(textBoxRequestCounter.Text)*3 / 4))
            //    toolStripProgressBar1.ForeColor = System.Drawing.Color.BlueViolet;
            toolStripProgressBar1.ProgressBar.ForeColor = System.Drawing.Color.Blue;
        }
        private void AddHistory() {
            urlhistory[ListBoxURL.SelectedIndex].Add(listBoxProxy.SelectedItem.ToString());
        }
        private void Wait_tick(object sender, System.EventArgs e) {
            WaitCountertoolStripStatusLabel4.Text = (Convert.ToInt32(WaitCountertoolStripStatusLabel4.Text) - 1).ToString();
            startToolStripMenuItemStart.Enabled = false;
            disableProxyToolStripMenuItem.Enabled = false;
            internetPropertiesToolStripMenuItem.Enabled = false;
            if (Convert.ToInt32(WaitCountertoolStripStatusLabel4.Text) <= 0) {
                WaitCounter.Stop();
                startToolStripMenuItemStart.Enabled = true;
                disableProxyToolStripMenuItem.Enabled = true;
                internetPropertiesToolStripMenuItem.Enabled = true;
                //WaitCountertoolStripStatusLabel4.Text = 0.ToString();
            }
        }
        public void Delay(int sec) {
            WaitCountertoolStripStatusLabel4.Text = WaitingAmount.ToString();
            try { 
                while ((Convert.ToInt32(WaitCountertoolStripStatusLabel4.Text) > 0)) {
                    Application.DoEvents(); // Allow windows messages to be processed
                    var t = new Thread(() => Thread.Sleep(1000));
                    t.Start();
                    t.Join();
                    WaitCountertoolStripStatusLabel4.Text = (Convert.ToInt32(WaitCountertoolStripStatusLabel4.Text) - 1).ToString();
                }
            } catch {
                InfostoolStripStatusLabel.Text = "Delay Exception!";
            }
        }
        private void Form1_Load(object sender, System.EventArgs e) {
            TestDataLoad();
        }
        private void TestDataLoad() {
            if (Convert.ToInt32(textBoxRequestCounter.Text) == 2) {
                string desktoppath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
                string[] lstring;
                if (System.IO.File.Exists(desktoppath + "\\proxy.txt")) {
                    lstring = File.ReadAllLines(desktoppath + "\\proxy.txt", System.Text.Encoding.Default);
                    LoadProxy(lstring);
                }
                if (System.IO.File.Exists(desktoppath + "\\url.txt")) {
                    lstring = File.ReadAllLines(desktoppath + "\\url.txt", System.Text.Encoding.Default);
                    LoadUrl(lstring); 
                }
            }
        }
        private static MainMenu _DefaultInstance;
        public static MainMenu DefaultInstance {
            get {
                if (_DefaultInstance == null)
                    _DefaultInstance = new MainMenu();

                return _DefaultInstance;
            }
        }
        public void LoadUrl(string[] lstring) {
            ListBoxURL.Items.AddRange(lstring);
            for (int i = 0; i < ListBoxURL.Items.Count; i++)
                if (ListBoxURL.Items[i].ToString() == " " || ListBoxURL.Items[i].ToString() == "" || string.IsNullOrEmpty(ListBoxURL.Items[i].ToString()))
                    ListBoxURL.Items.RemoveAt(i);
            if (ListBoxURL.Items[ListBoxURL.Items.Count-1].ToString() == "")
                ListBoxURL.Items.RemoveAt(ListBoxURL.Items.Count - 1);
            for (int i = 0; i < ListBoxURL.Items.Count; i++) {
                int count=0;
                foreach (UrlHistory item in urlhistory)
                    if (item.Url == ListBoxURL.Items[i].ToString())
                        count += 1;
                if (count <= 0) {
                    UrlHistory history = new UrlHistory();
                    history.Url = ListBoxURL.Items[i].ToString();
                    urlhistory.Add(history);
                }
            }
            GroupBoxURL.Text = "URL : " + ListBoxURL.Items.Count;
        }
        public void LoadProxy(string[] lstring) {
            listBoxProxy.Items.AddRange(lstring);
            for (int i = 0; i < listBoxProxy.Items.Count; i++)
                if (listBoxProxy.Items[i] == "")
                    listBoxProxy.Items.RemoveAt(i);
            if (listBoxProxy.Items[listBoxProxy.Items.Count - 1].ToString() == "")
                listBoxProxy.Items.RemoveAt(listBoxProxy.Items.Count - 1);
            GroupBoxProxy.Text = "Proxy : " + listBoxProxy.Items.Count;
        }     
        public void LoadFromText(string title) {
            OpenFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            OpenFileDialog1.Title = title;
            OpenFileDialog1.DefaultExt = ".txt";
            OpenFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            OpenFileDialog1.FilterIndex = 1;
            if (OpenFileDialog1.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) {
                string[] lstring = File.ReadAllLines(OpenFileDialog1.FileName, System.Text.Encoding.Default);
                if (title == "PROXY") {
                    listBoxProxy.Items.Clear();
                    LoadProxy(lstring);
                } else if (title == "URL") {
                    ListBoxURL.Items.Clear();
                    LoadUrl(lstring);
                }
            }
        }
        private void SaveStrongProxy() { 
        
        }
        private void textBoxRequestCounter_TextChanged(object sender, EventArgs e) {
            if (!RequestCounterTypeControl()) {
                MessageBox.Show("Request Counter Type is Not Number");
                toolStripProgressBar1.Maximum = 100;
            } else
                toolStripProgressBar1.Maximum = Convert.ToInt32(textBoxRequestCounter.Text);
        }
        private bool RequestCounterTypeControl() {
            try {
                Convert.ToInt32(textBoxRequestCounter.Text);
                return true;
            } catch (FormatException e) {
                return false;
            }
        }
        private bool ClickWaitTypeControl() {
            try {
                Convert.ToInt32(textBoxRequestCounter.Text);
                return true;
            } catch (FormatException e) {
                return false;
            }
        }
        private bool DelayTypeControl() {
            try {
                Convert.ToInt32(textBoxDelay.Text);
                return true;
            } catch (FormatException e) {
                return false;
            }
        }
        private void startToolStripMenuItemStart_Click(object sender, EventArgs e) {
            //(new Thread(new ThreadStart(SkipButtonClicked))).Start();
            Start();
            //backgroundWorker1.RunWorkerAsync();
        }
        private void restartToolStripMenuItemRestart_Click(object sender, EventArgs e) {
            HRNProxy.DisableProxy();
            Application.Restart();
        }
        private void disableProxyToolStripMenuItem_Click(object sender, EventArgs e) {
            HRNProxy.DisableProxy();
        }
        private void ProcessHistorytoolsToolStripMenuItem_Click(object sender, EventArgs e) {
            ProcessHistory processHistory = new ProcessHistory();
            processHistory.Show();
        }
        private void internetPropertiesToolStripMenuItem_Click(object sender, EventArgs e) {
            HRNProxy.OpenLanSettings();
        }
        private void loadUrlToolStripMenuItem_Click(object sender, EventArgs e) {
            LoadFromText("URL");
        }
        private void loadProxyToolStripMenuItem_Click(object sender, EventArgs e) {
            LoadFromText("PROXY");
        }
        private void WebBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
            if (IsCanClick()) {
                InfostoolStripStatusLabel.Text = "Navigated browser.";
                Wait(WaitingAmount = Convert.ToInt32(textBoxClickWait.Text));
                WebBrowser1.Document.Body.Style = "zoom:50%;";
                ClickSkipButton();
            }
        }
        public HtmlElement GetElementFromPoint() {
            Point ScreenCoord = new Point(MousePosition.X, MousePosition.Y);
            Point BrowserCoord = WebBrowser1.PointToClient(ScreenCoord);
            return  WebBrowser1.Document.GetElementFromPoint(BrowserCoord);
        }
        private void deleteSelectedLinkToolStripMenuItem_Click(object sender, EventArgs e) {
            if (ListBoxURL.SelectedItem!=null)
                ListBoxURL.Items.Remove(ListBoxURL.SelectedItem);
        }
        private void deleteSelectedProxyToolStripMenuItem_Click(object sender, EventArgs e) {
            listBoxProxy.Items.Remove(listBoxProxy.SelectedItem);
        }
        private void deleteAllToolStripMenuItem_Click(object sender, EventArgs e) {
            listBoxProxy.Items.Clear();
        }
        private void contextMenuStripProxy_Opening(object sender, System.ComponentModel.CancelEventArgs e) {
            if (listBoxProxy.SelectedItem == null)
                deleteSelectedProxyToolStripMenuItem.Enabled = false;
            else
                deleteSelectedProxyToolStripMenuItem.Enabled = true;
        }
        private void deleteAllToolStripMenuItem1_Click(object sender, EventArgs e) {
            ListBoxURL.Items.Clear();
        }
        private void contextMenuStripURL_Opening(object sender, System.ComponentModel.CancelEventArgs e) {
            if (ListBoxURL.SelectedItem == null)
                deleteSelectedLinkToolStripMenuItem.Enabled = false;
            else
                deleteSelectedLinkToolStripMenuItem.Enabled = true;
        }
        private void WebBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e) {
            if (IsCanClick()) {
                InfostoolStripStatusLabel.Text = "Navigated browser.";
                Wait(WaitingAmount = Convert.ToInt32(textBoxClickWait.Text));
                WebBrowser1.Document.Body.Style = "zoom:50%;";
                ClickSkipButton();
            }
        }
        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) {
            e.Result = Start();
        }
        private void textBoxClickWait_TextChanged(object sender, EventArgs e) {
            if (!ClickWaitTypeControl())
                MessageBox.Show(" Click Wait Type is Not Number");
        }
        private void addLinksToolStripMenuItem_Click(object sender, EventArgs e) {
            AddLinkOrProxy addLinkOrProxy = new AddLinkOrProxy();
            addLinkOrProxy.ShowDialog();
        }
        private void addProxysToolStripMenuItem_Click(object sender, EventArgs e) {
            AddLinkOrProxy addLinkOrProxy = new AddLinkOrProxy();
            addLinkOrProxy.ShowDialog();
        }
        private void textBoxDelay_TextChanged(object sender, EventArgs e) {
            if (!DelayTypeControl())
                MessageBox.Show(" Delay Type is Not Number");
        }
        private void downloadProxyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string url;
            string xml="";
            bool Downloadsuccess = false;
            for (int i = 0; i < 5; i++)
            {
                try
                {
                    if(i==0)
                        url = "http://freeproxylist.co/free-proxy-list-for-" + DateTime.Now.Date.ToString("yyyy-MM-dd") + "/";
                    else
                        url = "http://freeproxylist.co/free-proxy-list-for-" + DateTime.Now.Date.AddDays(-i).ToString("yyyy-MM-dd") + "/";
                    xml = new WebClient().DownloadString(url);
                    Downloadsuccess = true;
                    break;
                } catch { MessageBox.Show("Proxy Web Url not Found!"); }
            }
            if (Downloadsuccess)
            {
                string proxyStr = @"<div class=""entry_content"" id=""copy_div"">";
                int pos1 = xml.IndexOf(proxyStr);
                int pos2 = xml.IndexOf("</p>", pos1);
                string proxylist = xml.Substring(pos1, pos2 - pos1).Replace(proxyStr, "").Replace("<br>", "").Replace("\r\n", "").Replace("<br />", "").Replace("        <p>", "");
                listBoxProxy.Items.Clear();
                LoadProxy(proxylist.Split(Environment.NewLine.ToCharArray()));
                if (System.IO.File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\proxy.txt")) {
                    File.WriteAllLines(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\proxy.txt", proxylist.Split(Environment.NewLine.ToCharArray()));
                }
            }
            MessageBox.Show("Proxy Downloaded.");
        }
        private void stopToolStripMenuItem_Click(object sender, EventArgs e) {
            if (stopToolStripMenuItem.Text == "Stop") {
                stopToolStripMenuItem.Text = "Continue";
            } else {
                stopToolStripMenuItem.Text = "Stop";
            } while (stopToolStripMenuItem.Text == "Continue") {
                Application.DoEvents();
            }
        }

        private void WebBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e) {
            //if (WebBrowser1.ReadyState != WebBrowserReadyState.Uninitialized)
            //    while (WebBrowser1.ReadyState == WebBrowserReadyState.Loading)
                    Application.DoEvents();
        }

        private void MainMenu_FormClosed(object sender, FormClosedEventArgs e) {
            HRNProxy.DisableProxy();
        }

    }
}